package servlet;

import dao.ArticleDao;
import dao.CollectionDao;
import dao.daoimpl.ArticleDaoImpl;
import dao.daoimpl.CollectionDaoImpl;
import bean.Article;
import bean.Collection;
import bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/*收藏博客服务器*/
@WebServlet(name="AddCollectionServlet",urlPatterns = "/AddCollectionServlet")
public class AddCollectionServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");/*防止乱码*/
        int articleId=Integer.parseInt(request.getParameter("addCollectionArticleId"));/*博客id*/
        CollectionDao collectionDao=new CollectionDaoImpl();/*收藏接口的实现类*/
         ArticleDao articleDao=new ArticleDaoImpl();/*文章接口的实现类*/
        User user=(User)request.getSession().getAttribute("user");/*获取用户*/
        try{
            if(collectionDao.addCollection(new Collection(user.getAccount(),articleId))){/*添加进行收藏操作*/
                System.out.println("添加收藏成功");
                for(Article article:articleDao.getCollectedArticles(user)){
                    System.out.println(article.getTitle());
                }
                request.getSession().setAttribute("userCollections",articleDao.getCollectedArticles(user));/*返回用户收藏集合*/
                request.getSession().setAttribute("userCollected",collectionDao.getCollections(user));
                request.getSession().setAttribute("allPage",articleDao.getPage(user));
            }else{
                System.out.println("添加收藏失败");
            }
        } catch (SQLException sqlException) {
            sqlException.printStackTrace();
        }
    }
}
